using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ContentOverContainer.Common;
using ContentOverContainer.Common.Converter;
using Roslyn.Compilers.CSharp;

namespace ContentOverContainer.Converter.Converter
{
    public static class ReturnConverter
    {
        /// <summary>
        /// Converts the return expression.
        /// </summary>
        /// <param name="exprSyntax">The expression syntax.</param>
        /// <param name="pConverterData">The converter data.</param>
        /// <author>Harald Binkle</author>
        public static ChangeNodeInfo ConvertReturnExpression(ReturnStatementSyntax pExprSyntax, ConverterContext pConverterData)
        {
            var returnExpr = pExprSyntax.Expression;
            var returnMutiKind = pConverterData.MultiplicityInfo.Kind;
            var returnValue = returnExpr as SimpleNameSyntax; //This restricts the returns to a member, expressions and parameters do notyet work
            var valueDecl = returnValue.GetMemberDeclaration(pConverterData.SemanticModel);
            if (valueDecl != null)
            {
                var valueMultiKind = valueDecl.GetMultiplicityKind();

                if (returnMutiKind == MultiplicityKind.Any && valueMultiKind != MultiplicityKind.Any) //R-Return2
                {
                    var collectionType = pConverterData.MultiplicityInfo.Type as GenericNameSyntax;
                    var collectionOfType =
                        collectionType.TypeArgumentList.DescendantNodes().First(x => x is IdentifierNameSyntax);
                    var casted = CastConverter.UpcastToAny(returnExpr, Syntax.ParseTypeName(collectionOfType.ToString()),
                                                           returnExpr, collectionType.Identifier.ToString());
                    casted.OrgSyntaxNode = returnExpr;
                    return casted;
                }
            }
            return new ChangeNodeInfo(returnExpr) { OrgSyntaxNode = returnExpr}; //R-Return1
        }
    }
}
